package com.guqin.interview.controller;

import com.guqin.interview.common.BaseResponse;
import com.guqin.interview.common.ErrorCode;
import com.guqin.interview.common.ResultUtils;
import com.guqin.interview.exception.BusinessException;
import com.guqin.interview.model.dto.question.QuestionQueryRequest;
import com.guqin.interview.model.entity.Question;
import com.guqin.interview.model.entity.User;
import com.guqin.interview.model.vo.DailyQuestionCountVO;
import com.guqin.interview.model.vo.QuestionHistoryVO;
import com.guqin.interview.service.QuestionHistoryService;
import com.guqin.interview.service.UserService;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

/**
 * 题目历史接口
 */
@RestController
@RequestMapping("/question/history")
public class QuestionHistoryController {

    @Resource
    private QuestionHistoryService questionHistoryService;

    @Resource
    private UserService userService;

    /**
     * 记录用户查看题目
     *
     * @param questionId 题目id
     * @param request
     * @return 是否成功
     */
    @PostMapping("/record")
    public BaseResponse<Boolean> recordQuestionView(@RequestParam Long questionId, HttpServletRequest request) {
        if (questionId == null) {
            return ResultUtils.error(40000, "参数错误");
        }
        Long userId = userService.getLoginUser(request).getId();
        boolean result = questionHistoryService.recordQuestionView(userId, questionId);
        return ResultUtils.success(result);
    }

    /**
     * 获取用户某天查看的题目列表
     *
     * @param date 日期（格式：yyyy-MM-dd）
     * @param request
     * @return 题目列表
     */
    @GetMapping("/list")
    public BaseResponse<List<QuestionHistoryVO>> getUserQuestionsByDate(
            @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd") Date date,
            HttpServletRequest request) {
        if (date == null) {
            return ResultUtils.error(40000, "参数错误");
        }
        Long userId = userService.getLoginUser(request).getId();
        List<QuestionHistoryVO> questions = questionHistoryService.getUserQuestionsByDate(userId, date);
        return ResultUtils.success(questions);
    }


    /**
     * 获取用户某年的每日题目统计
     *
     * @param year 年份（为空表示当前年份）
     * @param request 请求
     * @return 每日题目统计列表
     */
    @GetMapping("/yearly/count")
    public BaseResponse<List<DailyQuestionCountVO>> getYearlyQuestionCount(@RequestParam(required = false) Integer year, HttpServletRequest request) {
        User loginUser = userService.getLoginUser(request);
        if (loginUser == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }
        List<DailyQuestionCountVO> dailyCountList = questionHistoryService.getYearlyQuestionCount(loginUser.getId(), year);
        return ResultUtils.success(dailyCountList);
    }
} 